/**
 * Created by hxpeng on 2017/4/27.
 */

(function () {
    'use strict';

    angular.module('App.common')
        .factory("LoginAccountAuth",LoginAccountAuth)


    function LoginAccountAuth(store,AppUtils,$q,Global,$http) {

        var service = {};
        service.isLoginIn = isLoginIn;
        service.getAccount = getAccount;
        service.setAccount = setAccount;
        service.httpGetLoginAccount =httpGetLoginAccount;
        service.getLastGotoUrl = getLastGotoUrl;
        service.setLastGotoUrl = setLastGotoUrl;
        return service;

        function isLoginIn(){
            var obj = store.get("loginAccount");
            if(AppUtils.isUndefinedOrNull(obj) || AppUtils.isUndefinedOrNull(obj.memberId)){
                return false;
            }else{
                return true;
            }
        }

        /**
         * 获取用户信息
         * @returns {*}
         */
        function getAccount(){
            var deferred = $q.defer();
            var account = store.get("loginAccount");
            if(AppUtils.isUndefinedOrNull(account)) {
                httpGetLoginAccount()
                    .then(function (data) {
                        if (data !== null) {
                            deferred.resolve(data);
                        }
                    });
            }else{
                deferred.resolve(account);
            }
            return deferred.promise;
        }


        /**
         * 临时缓存获取不到用户信息时，从后台获取
         * @returns {*}
         */
        function httpGetLoginAccount(){
            var deferred = $q.defer();
            $http.post(Global.path.server_wechat_test_path, {})
                .success(function (response) {
                    var obj = response.loginAccountVo;
                    setAccount(obj);
                    deferred.resolve(obj);
                })
                .error(function (data) {
                    deferred.reject(data);
                    AppUtils.showAlert("请求异常，请稍后再试！");
                })
            return deferred.promise;
        }

        /**
         * 将用户信息存入临时缓存中
         * @param account
         */
        function setAccount(account){
            store.set('loginAccount', account);
        }

        /**
         * 保存被拦截之前要访问的URL
         */
        function setLastGotoUrl(url){
            store.set('goToUrl', url);
        }

        /**
         * 获取被拦截之前要访问的URL
         */
        function getLastGotoUrl(){
            return store.get('goToUrl');
        }
    }
})();
